package com.love.sandl.tool.http

import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody

/**
 * @author Siaze
 * Http请求工具
 */
class HttpRequest {
    companion object {
        /**
         *  请求的client
         */
        private val client: OkHttpClient = OkHttpClient()

        init {

        }
    }

    /**
     * 请求的url
     */
    var url: String

    /**
     *请求头
     */
    var headers: HashMap<String, String>? = null

    /**
     * 请求的get参数
     */
    var urlParams: HashMap<String, String>? = null

    /**
     * resultFul参数
     */
    var resultFulParams: ArrayList<String>? = null

    /**
     * 请求的body
     */
    lateinit var requestBody: RequestBody

    init {
        this.resultFulParams = ArrayList()
        this.urlParams = HashMap()
        this.headers = HashMap()
    }

    constructor(
        url: String,
        urlParams: HashMap<String, String>,
        resultFulParams: ArrayList<String>,
        requestBody: RequestBody
    ) {
        this.url = url
        this.urlParams = urlParams
        this.resultFulParams = resultFulParams
        this.requestBody = requestBody
    }

    constructor(url: String) {
        this.url = url
    }

    /**
     * 添加get参数
     * @param k key变量名
     * @param v value变量值
     */
    fun putUrlParam(k: String, v: String) {
        this.urlParams?.set(k, v)
    }

    /**
     * 通过key获取URL参数值
     * @param k key
     */
    fun getUrlParam(k: String): String? {
        return urlParams?.get(k)
    }

    /**
     * 放入一个resultFul参数
     * @param param 参数的值
     */
    fun putResultFulParam(param: String) {
        resultFulParams?.add(param)
    }

    /**
     * 发生请求
     */
    fun sendGetRequest(callback: Callback) {
        val requestBuilder: Request.Builder = Request.Builder()
        /*
            ResultFul参数添加
         */
        if (this.url.endsWith("/")) this.url.plus('/')

        for (resultFulParam in this.resultFulParams!!) {
            this.url.plus(resultFulParam).plus('/')
        }
        /*
            url参数添加
         */
        if (urlParams!!.isNotEmpty()) this.url.plus('?')
        for (urlParam in this.urlParams!!) {
            this.url.plus(urlParam.key).plus(urlParam.value).plus('&')
        }
        requestBuilder.url(this.url)
        /*
            请求头添加
         */
        for (header in this.headers!!) {
            requestBuilder.addHeader(header.key, header.value)
        }

        /*
            异步请求回调
         */
        client.newCall(requestBuilder.get()?.build()).enqueue(callback)
    }

}